package com.crawler.waf.security.authentication.bearer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.crawler.waf.security.authens.BaseUserInfo;
import com.crawler.waf.security.authens.UserCenterUserDetails;
import com.crawler.waf.security.authens.UserRole;
import com.crawler.waf.security.authens.UserToken;
import com.crawler.waf.security.authens.WafUserAuthentication;
import com.crawler.waf.security.services.TokenService;
import com.crawler.waf.security.services.UserDetailsService;
import com.crawler.waf.support.Constants;

@Component
@Order(10)
public class BearerTokenAuthenticationProvider implements AuthenticationProvider {
	
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static Map<String, Object> bearerUserInfos = new HashMap<String, Object>();


	@Autowired
	public void setUcUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Autowired
	public void setTokenService(@Qualifier("bearer_token_service")TokenService ucBearerTokenService) {
		this.ucBearerTokenService = ucBearerTokenService;
	}

	/**
	 * 负责获得用户信息，WafAuthenticationProvider注入的是UserCenterUserDetailsService
	 */
	private UserDetailsService userDetailsService;

	/**
	 * tokenService负责在Uc验证用户传递token的有效性
	 */
	private TokenService ucBearerTokenService;
	
	
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	Assert.notNull(authentication, "authentication");
        PreAuthenticatedBearerTokenAuthentication bearerTokenAuthentication = (PreAuthenticatedBearerTokenAuthentication) authentication;
		//验证token
		UserToken token = ucBearerTokenService.verifyToken(bearerTokenAuthentication);
		
		UserCenterUserDetails userDetials = null;
		WafUserAuthentication authertication = null;
		if (token!=null) {
			ArrayList<UserRole> roles = new ArrayList<UserRole>();
			UserRole roleDeatail = new UserRole();
			roleDeatail.setRoleName(Constants.ROLE_BEARER);
			roles.add(roleDeatail);
			String userId = token.getUserId();
			BaseUserInfo userInfo = (BaseUserInfo)bearerUserInfos.get(userId);
			if (userInfo==null) {
				userInfo = userDetailsService.getUserInfo(userId);
				if (userInfo!=null) {
					bearerUserInfos.put(userId, userInfo);
				}
			}
			if (userInfo!=null) {
				userInfo.setUserType("Bearer");
				logger.info("WafAuthenticationProvider#authenticate: userId:"+userId);
				userDetials = new UserCenterUserDetails(userInfo, roles);
				authertication = new WafUserAuthentication(userDetials.getAuthorities());
				authertication.setAuthenticated(true);
				authertication.setDetails(userDetials);
			}
		}
		return authertication;
    }


    @Override
    public boolean supports(Class<?> authentication) {
        return authentication == PreAuthenticatedBearerTokenAuthentication.class;
    }
}
